package auctionClient;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.security.KeyPair;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.util.Scanner;
import java.util.Timer;
import java.util.TimerTask;

import javax.crypto.Cipher;

import org.bouncycastle.openssl.PEMReader;
import org.bouncycastle.openssl.PasswordFinder;

import auctionServer.Notifier;
import auctionServer.ServerReplica;

public class SignedBidSender implements Runnable{

	private TcpConnection connection;
	private String line;
	private Timer timer;
	private boolean serverIsOnline;
	private int price;
	private int auctionID;
	public SignedBidSender(TcpConnection connection, String line, int price, int auctionID){
		this.connection=connection;
		this.line=line;
		this.serverIsOnline=false;
		this.price=price;
		this.auctionID=auctionID;
		this.timer=new Timer();
	}
	
	public void run(){
		timer.schedule( new TimerTask() {
		    public void run() {
		    checkIsServerOnline();
		    
		    if(serverIsOnline){
		    	connection.appendMessage((line).getBytes());
				String response=new String (connection.getMessage());
				String command = response.substring(0, response.indexOf("@"));
				String message = response.substring(response.indexOf("@") + 1, response.length());
				
				if(command.equals("bid accepted")){
					System.out.println("You succesfully bid with "+price+" with id "+auctionID+" on "+message);
				}else if(command.equals("bid denied")){
					System.out.println("You unsuccesfully bid with "+price+" with id "+auctionID+" on "+message);
				}else if(command.equals("not found")){
					System.out.println("Auction with id "+auctionID+" isn't active.");
				}
				timer.cancel();
		    }else{

		    }
		   
		    }
		 }, 0, 1*1000);
	
		
	}
	private void checkIsServerOnline(){
		if(serverIsOnline){
			connection.appendMessage("!isAlive?".getBytes());
			try{
				String message=new String(connection.getMessage());
				if(message.equals("I/O Read Error at client Side at the Socket")){
					serverIsOnline=false;
					connection.close();
				}else serverIsOnline=true;
			}catch(java.lang.NullPointerException e){
				serverIsOnline=false;
				connection.close();
			}
		}else{
			connection=new TcpConnection(connection.getTcpPort(), connection.getHost());
			try {
				connection.connect();
				serverIsOnline=true;
			} catch (IOException e1) {
			}
		}
	}
}
